import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { ImgCropProps } from 'antd-img-crop';
import ImgCrop from 'antd-img-crop';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, { useState } from 'react';
import { getSign } from './service';
import Compressor from 'compressorjs';

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

type ImgUrl = string;
interface compressorProps {
    quality?: number;
    maxWidth?: number;
    maxHeight?: number;
}

interface ImgUploadProps {
    id?: string;
    value?: ImgUrl;
    accessId?: string;
    accessSecret?: string;
    needCrop?: boolean;
    needCompress?: boolean;
    cropProps?: ImgCropProps;
    resizeProps?: compressorProps;
    onChange?: (value: ImgUrl) => void;
}

const ImgUpload: React.FC<ImgUploadProps> = ({
    id = '',
    value = '',
    accessId = '16562668728a4af697c421e3c1d88afe',
    accessSecret = 'd6a8056a8617ff313edebe41074dc5dc',
    needCrop = false,
    needCompress = true,
    cropProps, // 裁剪参数
    resizeProps = {
        // 图片压缩参数
        quality: 0.6, // 压缩力度 0 ～ 1 （1为不压缩）
    },
    onChange,
}) => {
    // let { accessId, accessSecret } = props
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const [fromUrl, setFromUrl] = useState<string>('');
    const [fromData, setFromdata] = useState<any>({});

    const beforeUpload = async (file: RcFile) => {
        return new Promise(async (resolve, reject) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('只能上传JPG/PNG格式图片!');
                return;
            }
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                message.error('图片大小不得超过10MB!');
                return;
            }
            console.log(file, 'file');
            const response = await getSign({});
            new Compressor(file, {
                ...resizeProps,
                success(res: any) {
                    const data: Record<string, any> = {};
                    data.policy = response.policy;
                    data.signature = response.signature;
                    data.ossaccessKeyId = response.accessId;
                    data.key =
                        response.dir +
                        response.fileName +
                        res.name.replace(/\s*/g, '').split('.')[0] +
                        '.' +
                        res.name.split('.')[res.name.split('.').length - 1];
                    data.dir = response.dir;
                    data.host = response.host;
                    setFromdata(data);
                    setFromUrl(data.host + '/' + data.key);
                    resolve(res);
                },
                error() {
                    message.error('图片压缩失败！');
                    reject(false);
                },
            });
        });
    };

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        console.log('info--', info);
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, (url) => {
                setLoading(false);
                setImageUrl(url);
                // props.avatar = fromUrl
            });
            onChange?.(fromUrl);
        }
        if (info.file.status === 'error') {
            setLoading(false);
            message.error('上传失败');
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传{needCrop}</div>
        </div>
    );
    return (
        <>
            {!needCrop ? (
                <Upload
                    id={id}
                    name="file"
                    listType="picture-card"
                    className="avatar-uploader"
                    data={fromData}
                    showUploadList={false}
                    action={fromData.host}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                >
                    {value || imageUrl ? (
                        <img src={value || imageUrl} alt="avatar" style={{ width: '80px', height: '80px' }} />
                    ) : (
                        uploadButton
                    )}
                </Upload>
            ) : (
                <ImgCrop {...cropProps}>
                    <Upload
                        id={id}
                        name="file"
                        listType="picture-card"
                        className="avatar-uploader"
                        data={fromData}
                        showUploadList={false}
                        action={fromData.host}
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {value || imageUrl ? (
                            <img src={value || imageUrl} alt="avatar" style={{ width: '80px', height: '80px' }} />
                        ) : (
                            uploadButton
                        )}
                    </Upload>
                </ImgCrop>
            )}
        </>
    );
};

export default ImgUpload;
